﻿using HCQ2_Common.Constant;
using HCQ2_Model;
using HCQ2_Model.DocModel.APIParam;
using HCQ2_Model.DocModel.APIResultModel;
using HCQ2_Model.ViewModel.WebAPI;
using HCQ2_Model.WeiXinApiModel.ResultApiModel;
using HCQ2WebAPI_Logic.BaseAPIController;
using HCQ2WebAPI_Logic.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using HCQ2_Model.WeiXinApiModel.Model;
using System.Net;
using System.Text;
using HCQ2_Common;
using Newtonsoft.Json.Linq;
using HCQ2_Model.VR.Params;
using HCQ2_Model.VR.Model;
using HCQ2_Model.ViewModel;
using HCQ2_Common.DD;

namespace HCQ2WebAPI_Logic.DocumentController
{
    /// <summary>
    ///  VR微信小程序，控制器
    /// </summary>
    public class VRWebChatAPIController: BaseWeiXinApiLogic
    {
        #region ✔1.0 上传头像 + async Task<WebApiResultJsonModel> UploadPicture()
        /// <summary>
        ///   上传头像
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiResultJsonModel> UploadPicture()
        {
            //获取用户编码
            string updateIcon = HttpContext.Current.Request["updateIM"];//是否更新网易云信头像 update
            string userid = HttpContext.Current.Request[AuthorityConstant.USER_ID];//用户编码
            T_User user = operateContext.bllSession.T_User.Select(s => s.user_guid.Equals(userid)).FirstOrDefault();
            //文件上传路径
            string pathServer = "/UpFile/userImg/";
            string uploadPath = request.MapPath(request.ApplicationPath + pathServer);
            if (!Directory.Exists(uploadPath))
                Directory.CreateDirectory(uploadPath);
            CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(uploadPath);
            if (provider.FileData.Count > 1)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "头像只允许上传一张图片！", null);
            //定义上传文件名称
            string upFileNames = string.Empty;
            try
            {
                //上传附件
                await Request.Content.ReadAsMultipartAsync(provider);
                //获取原始文件名称
                foreach (MultipartFileData file in provider.FileData)
                {
                    upFileNames = Path.GetFileName(file.LocalFileName);
                    break;
                }
                //判断是否获取到了附件名称
                if (string.IsNullOrEmpty(upFileNames))
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "头像附件原始文件名称异常，附件上传失败~", null);
                //判断原始是否有头像，有则删除
                if (!string.IsNullOrEmpty(user.user_img))
                {
                    if (user.user_img.IndexOf("http")<0 && File.Exists(request.MapPath(user.user_img)))
                        File.Delete(request.MapPath(user.user_img)); 
                }
                //修改新的头像地址
                user.user_img = "~" + pathServer + upFileNames;
                int mark = operateContext.bllSession.T_User.Modify(user, s => s.user_id == user.user_id, "user_img");
                if (mark > 0)
                {
                    string hurl = user.user_img.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                    if(!string.IsNullOrEmpty(updateIcon) && updateIcon.Equals("update"))
                    {
                        //需要更新网易云信头像
                        if (!string.IsNullOrEmpty(user.user_phone))
                            IMUtil.ExecuteRequest(6, "accid=" + user.user_phone + "&icon=" + hurl);   
                    }
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "头像上传成功！", hurl);
                }                   
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "头像上传失败！", null);
            }
            catch (Exception ex)
            {
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, ex.Message, null);
            }
        }
        #endregion

        #region ✔1.1 获取用户错误单词 + async Task<WebApiResultJsonModel> GetErrorWordByUser(ErrorWordParams model)
        /// <summary>
        ///  获取用户错误单词
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiResultJsonModel> GetErrorWordByUser(ErrorWordParams model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            int user_id = HCQ2UI_Helper.Session.SysPermissSession.ChangeIdByGuid(model.userid);
            List<UserErrorList> list = await operateContext.bllSession.T_VRErrorWord.GetErrorWordByUser(model, user_id);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "用户错误单词获取成功~", list);
        }
        #endregion

        #region ✔1.2 获取课件关卡信息 + WebApiResultJsonModel  GetCoursewareById(CoursewareParam model)
        /// <summary>
        ///  获取课件关卡信息
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        [HCQ2_Common.Attributes.SkipApi]
        public WebApiResultJsonModel GetCoursewareById(CoursewareParam model)
        {
            ModelState.Remove("userid");//移除必填项
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            int user_id = HCQ2UI_Helper.Session.SysPermissSession.ChangeIdByGuid(model.userid);
            List<VRCustomPassRecord> list = operateContext.bllSession.T_VRCustomPass.GetCustomList(user_id, model.file_id);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "成功获取课件关卡信息~", list);
        }
        #endregion

        #region ✔1.3 获取关卡单词信息 + WebApiResultJsonModel  GetWordByCourseware(WordCoursewareParam model)
        /// <summary>
        ///  获取关卡单词信息
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        [HCQ2_Common.Attributes.SkipApi]
        public WebApiResultJsonModel GetWordByCourseware(WordCoursewareParam model)
        {
            ModelState.Remove("userid");//移除必填项
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            List<T_VRCustomPassWord> list = operateContext.bllSession.T_VRCustomPassWord.Select(s => s.file_id == model.file_id && s.cp_id == model.cp_id);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "成功获取关卡单词信息~", list);
        }
        #endregion

        #region ✔1.4 获取单词释义信息 + WebApiResultJsonModel  GetWordSenseInfo(QueryWordSense model)
        /// <summary>
        ///  获取单词释义信息
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        [HCQ2_Common.Attributes.SkipApi]
        public WebApiResultJsonModel GetWordSenseInfo(QueryWordSense model)
        {
            ModelState.Remove("userid");//移除必填项
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            T_VRWordSense query = operateContext.bllSession.T_VRWordSense.Select(s => s.word.Equals(model.word, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "成功获取关卡单词信息~", query);
        }
        #endregion

        #region ✔1.5 获取登录用户成绩 + WebApiResultJsonModel  GetWordSenseInfo(WordSenseModel model)
        /// <summary>
        ///  获取登录用户成绩
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetScoreByLoginUser(UserScoreParam model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            int user_id = HCQ2UI_Helper.Session.SysPermissSession.ChangeIdByGuid(model.userid);
            List<UserScoreRankModel> list = operateContext.bllSession.T_VRExperienceRecord.GetScoreByUser(model, user_id);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "成功获取个人成绩~", list);
        }
        #endregion

        #region ✔1.6 获取比赛排行榜 + WebApiResultJsonModel  GetGameRank(GameRank model)
        /// <summary>
        ///  获取比赛排行榜
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetGameRank(GameRank model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            if (string.IsNullOrEmpty(model.file_code))
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "课件代码不能为空！", null);
            var file = operateContext.bllSession.T_DocumentInfo.FindSingle(s => s.file_code.Equals(model.file_code) && s.file_status == 5 && s.is_game == 1 && !s.if_remove && s.game_start != null && s.game_end != null);
            if(file == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前课件不存在或不属于比赛课件！", null);
            if (string.IsNullOrEmpty(model.cp_code))
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "关卡代码不能为空！", null);
            var pass = operateContext.bllSession.T_VRCustomPass.FindSingle(s => s.file_id == file.file_id && s.cp_code.Equals(model.cp_code));
            if (pass == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "课件下不存在当前关卡！", null);
            //判断当前课件是否为比赛课件           
            if(file==null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "当前课件不属于比赛课件~", "");
            List<GameRankModel> list = operateContext.bllSession.T_VRExperienceRecord.GetGameRankList(model, file.game_start, file.game_end);
            if (list == null || list.Count <= 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "根据条件未查询到比赛排行记录~", "");
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "获取比赛排行记录成功~", list);
        }
        #endregion

        #region ✔1.7 获取我的比赛排行榜名次 + async Task<WebApiResultJsonModel>  GetMyGameRank(MyGameRank model)
        /// <summary>
        ///  获取我的比赛排行榜名次
        ///  async Task：异步编程
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiResultJsonModel> GetMyGameRank(MyGameRank model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            var file = operateContext.bllSession.T_DocumentInfo.FindSingle(s => s.file_code.Equals(model.file_code) && s.file_status == 5 && s.is_game == 1 && !s.if_remove && s.game_start != null && s.game_end != null);
            if (file == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前课件不存在或不属于比赛课件！", null);
            if(file.game_start==null || file.game_end==null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "比赛课件开始，结束时间不能为空！", null);
            int user_id = HCQ2UI_Helper.Session.SysPermissSession.ChangeIdByGuid(model.userid);
            int mark = await operateContext.bllSession.T_VRExperienceRecord.GetMyGameRank(model, user_id, file.game_start.ToString(), file.game_end.ToString());
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, $"获取比赛排行榜占位成功，当前排在第{mark}位~", mark);
        }
        #endregion

        //*********************************************************2.0头记测试************************************************************

        #region ✔2.0 获取测试排行榜 + WebApiResultJsonModel  GetWordRank(WordRankParam model)
        /// <summary>
        ///  获取测试排行榜
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetWordRank(WordRankParam model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            if (model.file_id<=0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "课件代码不能为空！", null);
            var file = operateContext.bllSession.T_DocumentInfo.FindSingle(s => s.file_id==model.file_id && s.file_status == 5 && !s.if_remove);
            if (file == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前课件不存在或已下架！", null);
            if (model.cp_id<=0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "关卡代码不能为空！", null);
            var pass = operateContext.bllSession.T_VRCustomPass.FindSingle(s => s.file_id == file.file_id && s.cp_id==model.cp_id);
            if (pass == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "课件下不存在当前关卡！", null);
            int total;
            List<WordRankResult> list = operateContext.bllSession.T_VRHeadWordMain.GetWordRankList(model, out total);
            TableModel tModel = new TableModel()
            {
                total = total,
                rows = list
            };
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "成功获取测试排行榜记录~", tModel);
        }
        #endregion

        #region ✔2.1 获取最好成绩 + WebApiResultJsonModel  GetGameRank(WordMydRankParam model)
        /// <summary>
        ///  获取最好成绩
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetMyWordRank(WordMydRankParam model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            int user_id = HCQ2UI_Helper.Session.SysPermissSession.ChangeIdByGuid(model.userid);
            model.user_id = user_id;
            if (model.file_id <= 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "课件代码不能为空！", null);
            var file = operateContext.bllSession.T_DocumentInfo.FindSingle(s => s.file_id == model.file_id && s.file_status == 5 && !s.if_remove);
            if (file == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前课件不存在或已下架！", null);
            if (model.cp_id <= 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "关卡代码不能为空！", null);
            var pass = operateContext.bllSession.T_VRCustomPass.FindSingle(s => s.file_id == file.file_id && s.cp_id == model.cp_id);
            if (pass == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "课件下不存在当前关卡！", null);
            WordRankResult result = operateContext.bllSession.T_VRHeadWordMain.GetMyWordRank(model);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "成功获取用户最好成绩记录~", result);
        }
        #endregion

        #region ✔2.2 获取用户单词测试成绩列表 + WebApiResultJsonModel  GetMyWordList(WordCoreByUser model)
        /// <summary>
        ///  获取用户单词测试成绩列表
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetMyWordList(WordCoreByUser model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            if (model.file_id <= 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "课件代码不能为空！", null);
            var file = operateContext.bllSession.T_DocumentInfo.FindSingle(s => s.file_id == model.file_id && s.file_status == 5 && !s.if_remove);
            if (file == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前课件不存在或已下架！", null);
            if (model.cp_id <= 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "关卡代码不能为空！", null);
            var pass = operateContext.bllSession.T_VRCustomPass.FindSingle(s => s.file_id == file.file_id && s.cp_id == model.cp_id);
            if (pass == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "课件下不存在当前关卡！", null);
            int user_id = HCQ2UI_Helper.Session.SysPermissSession.ChangeIdByGuid(model.userid);
            List<WordRankUserResult> list = operateContext.bllSession.T_VRHeadWordMain.GetWordRankByUserList(model, user_id);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "成功获取用户单词测试列表~", list);
        }
        #endregion

        #region ✔2.3 获取测试详细记录 + WebApiResultJsonModel  GetMyWordDetial(WordMyDetial model)
        /// <summary>
        ///  获取测试详细记录
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetMyWordDetial(WordMyDetial model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            List<HeadWordDetailedResult> list = operateContext.bllSession.T_VRHeadWordMain.GetMyDetectionList(model.wh_id);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "成功获取测试详细记录~", list);
        }
        #endregion
    }
}